package com.gui.mianshiya.controller;

import com.gui.mianshiya.common.BaseResponse;
import com.gui.mianshiya.common.ResultUtils;
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatCompletion;
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatCompletionResponse;
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatMessage;
import io.github.lnyocly.ai4j.service.IChatService;
import io.github.lnyocly.ai4j.service.PlatformType;
import io.github.lnyocly.ai4j.service.factor.AiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@RestController
public class OpenAiController {

    // 使用线程安全的存储结构
    private static final Map<String, List<ChatMessage>> USER_HISTORY = new ConcurrentHashMap<>();

    // 最大历史记录数
    private static final int MAX_HISTORY_SIZE = 10;
    private List<ChatMessage> history = new ArrayList<>(); // 1. 创建历史消息列表
    // 注入Ai服务
    @Autowired
    private AiService aiService;
    
    @GetMapping("/chat")
    public BaseResponse<ChatCompletionResponse> getChatMessageStream(@RequestParam String question, HttpServletRequest request) throws Exception {


        // 1. 获取或创建用户会话ID
        HttpSession session = request.getSession(true);
        String sessionId = session.getId();

        // 2. 获取用户专属的历史记录
        List<ChatMessage> history = USER_HISTORY
                .computeIfAbsent(sessionId, k -> new CopyOnWriteArrayList<>());

        // 3. 添加用户提问到历史
        history.add(ChatMessage.withUser(question));

        // 4. 构建请求
        IChatService chatService = aiService.getChatService(PlatformType.DEEPSEEK);
        // 创建请求参数
        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model("deepseek-chat")
               .messages(new ArrayList<>(history))
                .build();
        // 5. 获取AI响应
        ChatCompletionResponse response = chatService.chatCompletion(chatCompletion);

        // 6. 添加AI回答到历史（需要根据实际响应结构调整）
        String aiResponse = extractResponseContent(response); // 实现响应解析方法
        history.add(ChatMessage.withAssistant(aiResponse));
        // 7. 控制历史记录长度
        if (history.size() > MAX_HISTORY_SIZE) {
            history = history.subList(history.size() - MAX_HISTORY_SIZE, history.size());
            USER_HISTORY.put(sessionId, new CopyOnWriteArrayList<>(history));
        }
       return ResultUtils.success(response);
    }
    private String extractResponseContent(ChatCompletionResponse response) {
        // 实现具体的响应内容提取逻辑
        // 示例：return response.getChoices().get(0).getMessage().getContent();
          return response.getChoices().get(0).getMessage().getContent().toString();
    }


}

